<script setup lang="ts">
import { addMenu, getMenu, getMenuList, upMenu, deleteMenu } from '@/api/system/menu/menu';
import { ElMessage, type FormInstance } from 'element-plus';
import { reactive, ref, toRefs } from 'vue';
import * as ElementPlusIconsVue from '@element-plus/icons-vue'
import message from '@/utils/message'
import { handleTree } from '@/utils/ruoyi';
interface Menu{
        id: number,
        name: string,
        path: string,
        component: string,
        icon: string,
        sort: number,
        parentId: number,
        isShow: number,
        perms: string,
        type: number,
        status: number,
        createTime: string,
        updateTime: string,
        children: Menu[]
}
//菜单数据
const menuList = ref()
const props = {
    label: "name",
    value: "id"
}
//表单校验
const nameValidator = (rule: any, value: any, callback: any) => {

  if (!value || value.trim() === '') {
                callback(new Error('名称不能为空'));
} else if (value.trim().length < 1 || value.trim().length > 10) {
    callback(new Error('长度为1到10位'))
} else {
    callback()
}
}
const data = reactive({
  form: <Menu>{
    parentId:0,
    type:0,
    isShow: 1,
    status:1,
    sort:0
  },
  rules: {
    name: [
        {
            required: true,
            validator: nameValidator,
            trigger: 'blur',
        },
    ],}
});
const {  form, rules } = toRefs(data);



// 获取菜单树形结构
async function ListMenuTree() {
  loading.value=true
    await getMenuList().then((data) => {
        menuList.value = handleTree(data.data.data, "id", "parentId", "children")
       //更新菜单
       localStorage.setItem("menu", JSON.stringify(data.data.data))
    })
    loading.value=false
}

//添加修改对话框
const dialogVisible = ref(false)
//对话框标题
const title = ref()
const loading =ref(false)
//修改操作
const handleUpdate = (item: any) => {
    title.value = "修改"
    dialogVisible.value = true
    isSumbit.value = false
    //获取菜单详细
    getMenu(item.id).then((data) => {
      form.value = data.data.data
    })

}
//提交按钮标识
const isSumbit = ref(false);
//新增操作
const handleAdd = (item?: any) => {
    title.value = "新增"
    isSumbit.value = true
    dialogVisible.value = true
    if (item.id !== null && item.id !== undefined) {
        //获取菜单详细
        getMenu(item.id).then((data) => {
            form.value.parentId = data.data.data.id
        })
    }
}
//删除
const handleDelete = async (item: any) => {
    if (item.children != null || item.children !=undefined) {
        ElMessage({
            message: '存在子菜单，不可删除.',
            type: 'warning',
        })
    } else {
        await deleteMenu(item.id).then((response) => {
    ElMessage.success(response.data.msg);
  });
    }
    ListMenuTree()
}

//提交按钮
const submitForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate(async (valid, fields) => {
        if (valid) {
            if (isSumbit.value) {
                await addMenu(form.value).then((response) => {
    ElMessage.success(response.data.msg);
  });
            } else {
                await upMenu(form.value).then((response) => {
    ElMessage.success(response.data.msg);
  });
            }
            dialogVisible.value = false
            ListMenuTree()
        }
    })
}

const formEl = ref()
//表单重置
const resetForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.resetFields()
}
ListMenuTree()
</script>
<template>
  <el-button type="primary" @click="handleAdd">新增</el-button>
  <el-divider />
  <el-table
    :data="menuList"
    v-loading="loading"
    row-key="id"
    :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
    style="width: 100%; height: 70vh"
  >
    <el-table-column
      prop="name"
      label="菜单名称"
      :show-overflow-tooltip="true"
      width="160"
    ></el-table-column>
    <el-table-column prop="icon" label="图标" align="center" width="100">
      <template #default="scope">
        <component style="width: 20px" :is="scope.row.icon" />
      </template>
    </el-table-column>
    <el-table-column prop="sort" label="排序" width="60"></el-table-column>
    <el-table-column
      prop="perms"
      label="权限标识"
      :show-overflow-tooltip="true"
    ></el-table-column>
    <el-table-column
      prop="component"
      label="组件路径"
      :show-overflow-tooltip="true"
    ></el-table-column>
    <el-table-column prop="status" label="状态" width="80">
      <template #default="scope">
        <el-tag :value="scope.row.status">{{
          scope.row.status ? "启用" : "停用"
        }}</el-tag>
      </template>
    </el-table-column>
    <el-table-column label="创建时间" align="center" width="160" prop="createTime">
      <template #default="scope">
        <span>{{ scope.row.createTime }}</span>
      </template>
    </el-table-column>
    <el-table-column
      label="操作"
      align="center"
      width="210"
      class-name="small-padding fixed-width"
    >
      <template #default="scope">
        <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
          >修改</el-button
        >
        <el-button link type="primary" icon="Plus" @click="handleAdd(scope.row)"
          >新增</el-button
        >
        <el-popconfirm title="确定要删除吗？" @confirm="handleDelete(scope.row)">
          <template #reference>
            <el-button link type="primary" icon="Delete">删除</el-button>
          </template>
        </el-popconfirm>
      </template>
    </el-table-column>
  </el-table>
  <!-- 添加修改 -->
  <el-dialog
    v-model="dialogVisible"
    :title="title"
    width="800"
    @close="resetForm(formEl)"
  >
    <el-form
      :model="form"
      ref="formEl"
      :rules="rules"
      style="max-width: 600px"
      label-width="auto"
    >
      <el-row>
        <el-col :span="24">
          <el-form-item prop="parentId" label="上级菜单">
            <el-tree-select
              v-model="form.parentId"
              :props="props"
              :data="menuList"
              check-strictly
              :render-after-expand="false"
              style="width: 240px"
            >
            </el-tree-select>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item prop="type" label="菜单类型">
            <el-radio-group v-model="form.type">
              <el-radio :value="0">目录</el-radio>
              <el-radio :value="1">菜单</el-radio>
              <el-radio :value="2">按钮</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="菜单图标" prop="icon">
            <el-select v-model="form.icon" placeholder="选择图标" style="width: 240px">
              <template #label>
                <span>
                  <component style="width: 20px; margin-right: 10px" :is="form.icon" />
                </span>
                <span> {{ form.icon }}</span>
              </template>
              <el-option
                v-for="item in ElementPlusIconsVue"
                :key="item.name"
                :label="item.name"
                :value="item.name"
              >
                <component style="width: 20px" :is="item" />
                <span style="margin-left: 10px">{{ item.name }}</span>
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12" v-show="form.type == 1">
          <el-form-item prop="perms" label="权限标识">
            <el-input v-model="form.perms" placeholder="请输入权限标识"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item prop="name">
            <template #label>
              <span v-if="form.type == 0">目录名称</span>
              <span v-else-if="form.type == 1">菜单名称</span>
              <span v-else-if="form.type == 2">按钮名称</span>
            </template>
            <el-input v-model.trim="form.name" placeholder="请输入菜单名称"></el-input>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="显示排序" prop="sort">
            <el-input-number v-model="form.sort" controls-position="right" :min="0" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="组件路径" prop="component">
            <el-input v-model="form.component" placeholder="请输入组件路径"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12" v-show="form.type == 1">
          <el-form-item prop="path">
            <template #label>
              <span>
                <el-tooltip
                  content="访问的路由地址，如：`user`，如外网地址需内链访问则以`http(s)://`开头"
                  placement="top"
                >
                  <el-icon><question-filled /></el-icon>
                </el-tooltip>
                路由地址
              </span>
            </template>
            <el-input v-model.trim="form.path" placeholder="请输入路由地址" />
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item prop="isShow" v-if="form.path != 'F'">
            <template #label>
              <span>
                <el-tooltip
                  content="选择隐藏则路由将不会出现在侧边栏，但仍然可以访问"
                  placement="top"
                >
                  <el-icon><question-filled /></el-icon>
                </el-tooltip>
                显示状态
              </span>
            </template>
            <el-radio-group v-model="form.isShow" v-if="form.path != 'F'">
              <el-radio :value="0">隐藏</el-radio>
              <el-radio :value="1">显示</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item prop="status">
            <template #label>
              <span>
                <el-tooltip content="选择停用则不会显示，也不能使用" placement="top">
                  <el-icon><question-filled /></el-icon>
                </el-tooltip>
                <span v-if="form.type == 0">目录状态</span>
                <span v-else-if="form.type == 1">菜单状态</span>
                <span v-else-if="form.type == 2">按钮状态</span>
              </span>
            </template>
            <el-radio-group v-model="form.status">
              <el-radio :value="0">禁用</el-radio>
              <el-radio :value="1">启用</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item>
            <el-button @click="submitForm(formEl)">确定</el-button>
            <el-button @click="dialogVisible = false">取消</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
  </el-dialog>
</template>
